﻿using System.Collections.Generic;
using System.Linq;
using Socium.Domain.Tests;
using Socium.Presentation;

namespace Socium.TestEditor {
	class TestTreeItem : TreeItemBase<Test, ClosedQuestionTreeItem> {
		readonly CommandViewModel[] _commands;

		public TestTreeItem(Test test, ICollection<TestTreeItem> items) : base(test) {
			_collection = items;

			_commands = new[] {
				new CommandViewModel("Properties...", new Command<IFormViewService>(OnDetails)),
				new CommandViewModel("New question", new Command<IFormViewService>(OnNewClosedQuestion)),
				new CommandViewModel("Delete", new Command<IFormViewService>(OnDelete)),
			};
		}

		void OnDelete(IFormViewService form_view_service) {
			//var manager = (IFormViewService) obj;
			_collection.Remove(this);
		}

		readonly ICollection<TestTreeItem> _collection;

		void OnDetails(IFormViewService form_view_service) {
			Details(form_view_service, model => new TestViewModel(model));
		}

		public override IEnumerable<CommandViewModel> Commands {
			get { return _commands; }
		}

		protected override string GetDisplayName(Test model) {
			return model.Name;
		}

		protected override IEnumerable<ClosedQuestionTreeItem> GetInitalChilderen(Test test) {
			var closed_questions = test.Questions.OfType<ClosedQuestion>();
			return closed_questions.Select(question => new ClosedQuestionTreeItem(question));
		}

		protected override void OnItemAdded(ClosedQuestionTreeItem item) {
			Model.Questions.Add(item.Model);
		}

		protected override void OnItemRemoved(ClosedQuestionTreeItem item) {
			Model.Questions.Remove(item.Model);
		}

		void OnNewClosedQuestion(IFormViewService form_view_service) {
			NewChild<ClosedQuestionViewModel, ClosedQuestion>(form_view_service, question => new ClosedQuestionTreeItem(question));
		}
	}
}
